<?php

namespace app\common;

use app\model\User;
use app\service\AesService;
use app\service\HomeService;
use Exception;
use support\Response;
use support\View;

class HomeBase
{
    public string $env             = '';
    public string $controller_name = '';
    public string $action_name     = '';

    public function beforeAction()
    {
        $this->env             = ENVIRONMENT;
        $static_version        = $this->env == 'PRO' ? '1.26' : time();
        $this->controller_name = substr(request()->controller, strrpos(request()->controller, '\\') + 1);
        $this->action_name     = request()->action;
        View::assign(compact('static_version'));
    }

    /**
     * @throws Exception
     */
    public function homeTpl(array $assign = [], string $template = ''): Response
    {
//        if (empty($template)) $template = strtolower($this->controller_name) . "/{$this->action_name}";
//        return view($template, array_merge($assign, []));
        if (empty($template)) $template = strtolower($this->controller_name) . "/{$this->action_name}";
        $env                 = $this->env;
        $uid                 = request()->uid;
        $user_vip_type       = request()->uid ? User::is_really_vip(request()->uid) : 0;
        $base_assign         = [
            'env'           => $env,
            'u_token'       => $uid ? AesService::instance()->encrypt(request()->u_token) : '',
            'action'        => $this->action_name, 'controller' => $this->controller_name,
            'is_vip'        => $user_vip_type > 0 ? 1 : 0,
            'member'        => $uid ? $this->getUserInfo($uid) : [],
        ];
        return view($template, array_merge($assign, $base_assign));
    }

    /**
     * SEO
     * @param array $seo
     * @return void
     */
    public function seo(array $seo)
    {
        View::assign(compact('seo'));
    }

    /**
     * @param int $uid
     * @return array
     */
    public function getUserInfo(int $uid): array
    {
        if (empty($uid)) return [];
        return User::getOne(['id' => $uid]);
    }

    /**
     * @return Response
     */
    public function jump404(): Response
    {
        return view('public/404', []);
    }

    /**
     * @param string $msg
     * @param string $url
     * @return Response
     */
    public function jumpError(string $msg = '', string $url = ''): Response
    {
        return view('public/error', compact('msg', 'url'));
    }

    public function apiSuccess($data = '', string $msg = 'success', $code = 0): Response
    {
        return json(['code' => $code ?: ApiStatus::API_SUCCESS->value, 'msg' => $msg, 'data' => $data]);
    }

    public function apiFailed(string $msg = 'error', int $code = 0): Response
    {
        return json(['code' => $code ?: ApiStatus::API_ERROR->value, 'msg' => $msg]);
    }
}